<template>
  <div class="box-card">
    <!-- 卡片頂部的添加品牌的按钮 -->
    <div class="button">
      <el-button type="primary" icon="Plus" @click="addTrademark"
        >添加品牌</el-button
      >
    </div>
    <!-- 表格：用于展示数据 -->
    <div class="tables">
      <el-table :data="data.tableData" border style="width: 100%; height: 100%">
        <el-table-column type="index" label="序号" width="80" align="center">
          <template #default="scope">
            {{ (data.currentPage - 1) * data.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #default="scope">
            <img
              :src="scope.row.logoUrl"
              alt="图片丢失了~"
              style="width: 60px; height: 60px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="品牌操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTradeMark(scope.row)"
              :title="'修改'"
            ></el-button>
            <el-popconfirm
              :title="`您确定删除${scope.row.tmName}`"
              width="250px"
              icon="delete"
              @confirm="removeTradeMark(scope.row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="Delete"
                  :title="'删除'"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        :size="size"
        :disabled="disabled"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <!-- 添加品牌弹框：对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 -->
  <el-dialog v-model="data.dialogFormVisible" :title="data.dialogTitle">
    <el-form
      style="width: 90%"
      :model="trademarkParams"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          placeholder="请您输入品牌名称"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  reqHasTradeMark,
  reqDeleteTrademark,
  reqAddOrUpdateTrademark,
} from "../../../api/product/trademark/index";
import {
  TradeMark,
  TradeMarkResponseData,
} from "../../../api/product/trademark/type";
import { UploadProps } from "element-plus/es/components/upload/src/upload";

// const background = ref(true)
const size = ref("default");
const disabled = ref(false);
const data = reactive({
  tableData: [], // 表格存储数据
  currentPage: 1,
  total: 0,
  pageSize: 10,
  dialogFormVisible: false, // 弹框的显示与隐藏
  dialogTitle: "添加品牌",
});
// form表单用的用于规格校验
const formRef = ref();

// 获取已有品牌数据
const trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});

onMounted(() => {
  getHasTrademark();
});

// 調用接口获取数据
const getHasTrademark = async () => {
  await reqHasTradeMark(data.currentPage, data.pageSize).then(
    (res: TradeMarkResponseData) => {
      if (res.code == 200) {
        data.tableData = res.data.records as [] as [];
        data.total = res.data.total as number;
      }
    },
  );
};
// 分页事件
//当下拉菜单发生变化的时候触发次方法
//这个自定义事件,分页器组件会将下拉菜单选中数据返回
function handleSizeChange(val: number) {
  console.log(`每页 ${val} 条`);
  data.pageSize = val;
  data.currentPage = 1;
  getHasTrademark();
}

function handleCurrentChange(val: number) {
  console.log(`当前页: ${val}`);
  data.currentPage = val;
  getHasTrademark();
}
// 表单 必填校验规则 自定义校验规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  // value：表单的值
  if (value.trim().length >= 2) {
    callBack(); //校验通过的放行函数
  } else {
    callBack(new Error("品牌名称位数大于等于两位"));
  }
};
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  // value：表单的值
  if (value) {
    callBack(); //校验通过的放行函数
  } else {
    callBack(new Error("Logo的图片务必上传"));
  }
};
const rules = {
  tmName: [
    //required:这个字段务必校验,表单项前面出来五角星
    //trigger:代表触发校验规则时机[blur、change] 焦点变化或者值改变的时候
    {
      required: true,
      trigger: "blur",
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: "change",
      validator: validatorLogoUrl,
    },
  ],
};

// 文件上传
// 上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传的文件大小应小于4M",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传的文件类型必须是PNG|JPG|GIF",
    });
    return false;
  }
};
// 图片上传成功的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
) => {
  console.log(uploadFile);
  // response:即为当前这次上传图片post请求服务器返回的数据
  trademarkParams.logoUrl = response.data;
  formRef.value.clearValidate("logoUrl");
};

//新增 添加
const addTrademark = () => {
  data.dialogTitle = "添加品牌";
  data.dialogFormVisible = true;
  // 添加的時候先清空缓存
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  // 清除掉对应表单中必填校验结果
  // nextTick：是一个非常有用的函数，它用于延迟执行某个函数，直到下次 DOM 更新循环结束之后。这有助于我们在修改数据后获取更新后的 DOM 状态。
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
};
//更新 品牌
const updateTradeMark = (item: any) => {
  // 清除掉对应表单中必填校验结果 ：清空校验规则错误提示信息
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });

  data.dialogFormVisible = true;
  data.dialogTitle = "修改品牌";
  // 赋值item里面的给页面  ES6语法合并对象
  Object.assign(trademarkParams, item);
};
// 弹框的事件 取消和确定
const cancel = () => {
  data.dialogFormVisible = false;
};
const confirm = async () => {
  // 保存的时候去校验表单必填规则
  // 校驗表單：所有的表单项校验通过在发送请求
  // 调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  await formRef.value.validate();

  let result: any = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code == 200) {
    // 提示信息
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功",
    });
    //再次调用获取已有品牌数据
    data.currentPage = trademarkParams.id ? data.currentPage : 1;
    getHasTrademark();
    //添加成功关闭弹框
    data.dialogFormVisible = false;
  } else {
    // 添加失败提示信息
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "修改品牌失败" : "添加品牌失败",
    });
  }
};
// 删除品牌 气泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
  let res = await reqDeleteTrademark(id);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    //再次获取已有的品牌数据
    data.currentPage =
      data.tableData.length > 1 ? data.currentPage : data.currentPage - 1;
    getHasTrademark();
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
</script>

<style scoped lang="scss">
.box-card {
  height: 100%;
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
  box-shadow: var(--el-box-shadow-light);
  border-radius: 5px;
}

.button {
  height: 40px;
  width: 100%;
}

.tables {
  flex: 1;
  box-sizing: border-box;
  overflow: hidden;
}

.pagination {
  margin-top: 10px;
  height: 40px;
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
